<!-- html -->
<template>
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <!-- 表单绑定 -->
        <el-form ref="goodsCategoryRef" :model="form" :rules="rules"  label-width="80px">
            <el-form-item label="分类名字" prop="name">
            <el-input v-model="form.name" placeholder="请输入分类名字" />
            </el-form-item>

            <el-form-item label="父类" prop="parentId">
            <el-tree-select
                v-model="form.parentId"
                :data="goodsCategoryOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                value-key="id"
                placeholder="请选择父类ID"
                check-strictly
            />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="submit" type="primary">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<!-- 
    ts 
   setup  支持setup语法糖
-->
<script lang="ts" setup>
    import {ref,toRefs,defineEmits,reactive,watch} from 'vue'

    //获取当前实例对象
    const { proxy } = getCurrentInstance();

    //接收父组件传入的属性
    let props = defineProps({
        title:{
            type: String,
            default: null
        },
        open:{
            type:Boolean,
            default:false
        },
        goodsCategoryOptions:{
            type:Array,
            default:[]
        },
        formInfo:{
            type:Object,
            default:null
        }
    })

    //定义form表单参数
    let form=reactive({
        id: null,
        name: null,
        parentId: null,
        sort: null,
        isDel: null
    })

    //表单校验规则
    let rules=reactive({
        name: [
        { required: true, message: "分类名字不能为空", trigger: "blur" }
        ],
        parentId: [
        { required: true, message: "父类ID不能为空", trigger: "blur" }
        ]
    })

    //从props提取指定属性
    let {title,open,formInfo} = toRefs(props)

    //定义事件
    let emits = defineEmits(['cancelBox','submitForm'])


    //定义关闭窗口方法
    function cancel(){
        emits('cancelBox')
    }

    //定义提交方法
    function submit(){
        proxy.$refs["goodsCategoryRef"].validate(valid => {
            if (valid) {
                emits('submitForm',form)
            }
        });
    }

    //监听一个对象的对象属性
    watch(()=>props.formInfo,(newValue,oldValue)=>{
        //变更的数据赋值给表单对象 form  深克隆
        form=JSON.parse(JSON.stringify(newValue))
    },{deep:true})

</script>
<!-- css样式 -->
<style scoped>
</style>